package a;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class IMFComERFetcher extends ExchangeRateFetcher {
	public enum FileReaderStat {
		Skip,Process,Done
	}

	@Override
	@SuppressWarnings("deprecation")
	public void fetch() {
		Date d = this.getDate();
		String queryUrl=String.format(
				"http://www.imf.org/external/np/fin/data/rms_mth.aspx?SelectDate=%d-%d-%d&reportType=CVSDR&tsvflag=Y",
				d.getYear()+1900,d.getMonth()+1,d.getDate());

		try {
			URL u = new URL(queryUrl);
			BufferedReader br = new BufferedReader(new InputStreamReader(u.openStream()));

			String line;
			String[] cells;
			int hitColumn = 0;
			FileReaderStat frs = FileReaderStat.Skip;
			while((line=br.readLine())!=null) {
				if(frs==FileReaderStat.Done) {
					break;
				}

				cells = line.split("\t");
				if(cells.length<2) {
					if(frs==FileReaderStat.Process) {
						frs=FileReaderStat.Done;
					} else {
						frs = FileReaderStat.Skip;
					}
					hitColumn = 0;
				} else {
					if(frs==FileReaderStat.Skip) {
						if(cells[0].equals("Currency")) {
							for(int i=1;i<cells.length;i++) {
								if(dateformat.parse(cells[i]).equals(d)){
									hitColumn = i;
									break;
								}
							}

							if(hitColumn>0){
								frs=FileReaderStat.Process;
							}
						}
					} else if (frs==FileReaderStat.Process) {
						if(EngCode.containsKey(cells[0])) {
							this.setRate(EngCode.get(cells[0]),
									cells[hitColumn].equals("NA")?Float.NaN:decformat.parse(cells[hitColumn]).floatValue(),
									"SDR");
						}
					}
				}
			}

			br.close();


			u = new URL("http://hq.sinajs.cn/rn=pna8n&list=USDHKD,USDTWD");
			br = new BufferedReader(new InputStreamReader(u.openStream(),Charset.forName("GBK")));
			Matcher m;
			while((line=br.readLine())!=null){
				if((m=sinaPattern.matcher(line)).matches()){
					this.setRate(m.group(1), Float.parseFloat(m.group(2).split(",")[1]), "USD");
				}
			}
			br.close();
		} catch (Exception e) {
			e.printStackTrace();
		}



	}

	private static final Pattern sinaPattern = Pattern.compile("var hq_str_USD(\\w{3})=\"(.+)\";");
	private static final SimpleDateFormat dateformat = new SimpleDateFormat("MMMM dd, yyyy",Locale.US);
	private static final DecimalFormat decformat = new DecimalFormat("#,###.#");
	private static final HashMap<String,String> EngCode = new HashMap<String,String>();
	static {
		EngCode.put("Euro","EUR");
		EngCode.put("Japanese Yen","JPY");
		EngCode.put("U.K. Pound Sterling","GBP");
		EngCode.put("U.S. Dollar","USD");
		EngCode.put("Algerian Dinar","DZD");
		EngCode.put("Argentine Peso","ARS");
		EngCode.put("Australian Dollar","AUD");
		EngCode.put("Bahrain Dinar","BHD");
		EngCode.put("Botswana Pula","BWP");
		EngCode.put("Brazilian Real","BRL");
		EngCode.put("Brunei Dollar","BND");
		EngCode.put("Canadian Dollar","CAD");
		EngCode.put("Chilean Peso","CLP");
		EngCode.put("Chinese Yuan","CNY");
		EngCode.put("Colombian Peso","COP");
		EngCode.put("Czech Koruna","CZK");
		EngCode.put("Danish Krone","DKK");
		EngCode.put("Hungarian Forint","HUF");
		EngCode.put("Icelandic Krona","ISK");
		EngCode.put("Indian Rupee","INR");
		EngCode.put("Indonesian Rupiah","IDR");
		EngCode.put("Iranian Rial","IRR");
		EngCode.put("Israeli New Sheqel","ILS");
		EngCode.put("Kazakhstani Tenge","KZT");
		EngCode.put("Korean Won","KRW");
		EngCode.put("Kuwaiti Dinar","KWD");
		EngCode.put("Libyan Dinar","LYD");
		EngCode.put("Malaysian Ringgit","MYR");
		EngCode.put("Mauritian Rupee","MUR");
		EngCode.put("Mexican Peso","MXN");
		EngCode.put("Nepalese Rupee","NPR");
		EngCode.put("New Zealand Dollar","NZD");
		EngCode.put("Norwegian Krone","NOK");
		EngCode.put("Rial Omani","OMR");
		EngCode.put("Pakistani Rupee","PKR");
		EngCode.put("Nuevo Sol","PEN");
		EngCode.put("Philippine Peso","PHP");
		EngCode.put("Polish Zloty","PLN");
		EngCode.put("Qatar Riyal","QAR");
		EngCode.put("Russian Ruble","RUB");
		EngCode.put("Saudi Arabian Riyal","SAR");
		EngCode.put("Singapore Dollar","SGD");
		EngCode.put("South African Rand","ZAR");
		EngCode.put("Sri Lanka Rupee","LKR");
		EngCode.put("Swedish Krona","SEK");
		EngCode.put("Swiss Franc","CHF");
		EngCode.put("Thai Baht","THB");
		EngCode.put("Trinidad And Tobago Dollar","TTD");
		EngCode.put("Tunisian Dinar","TND");
		EngCode.put("U.A.E. Dirham","AED");
		EngCode.put("Peso Uruguayo","UYU");
		EngCode.put("Bolivar Fuerte","VEF");
	}
}
